import type Want from '@ohos.app.ability.Want';
import wantConstant from '@ohos.app.ability.wantConstant';
import type { BusinessError } from '@ohos.base';
import type common from '@ohos.app.ability.common';
import { FileManager } from './FileManger';
import picker from '@ohos.file.picker';
import { MemBuffer } from 'coremail/src/main/ets/utils/file_stream';
import { getLogger } from 'coremail';

const logger = getLogger("AttachmentUtil");

export class AttachmentUtil {

  /**
   * 启动其他App来打开文件
   * @param context
   * @param filePath 文件本地存储路径
   */
  static openByOtherApp(context: common.UIAbilityContext, filePath: string): void {
    // https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/application-models/uiability-intra-device-interaction.md#%E5%90%AF%E5%8A%A8%E5%85%B6%E4%BB%96%E5%BA%94%E7%94%A8%E7%9A%84uiability
    let uri = FileManager.uri(filePath)
    let want: Want = {
      deviceId: '', // deviceId为空表示本设备
      action: 'ohos.want.action.viewData',
      // entities: ['entity.system.default'], // 居然不传才能打开正确，跟文档说的有出入
      uri: uri,
      flags: wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION,
    }
    context.startAbility(want).then(() => {
      logger.info('Succeeded in starting ability.');
    }).catch((err: BusinessError) => {
      logger.error(`Failed to start ability. Code is ${err.code}, message is ${err.message}`);
    })
  }

  static sizeString(size: number): string {
    let index = 0;
    let n = size != null ? size : 0;
    while (1) {
      if (n > 1024) {
        index++;
        n = n / 1024;
      }
      else {
        break;
      }
    }
    let unitArray = [`B`,'KB','MB',"GB"];
    return `${n.toFixed(2)}${unitArray[index]}`
  }

  /**
   * 将文件存到系统文件管理器
   * @param localPath 文件沙盒路径
   * @param fileType 文件类型
   * @param fileName 文件名
   */
  static async saveToSystemFileManager(localPath: string, fileType: string, fileName: string): Promise<void> {
    try {
      let buffer = await FileManager.readData(localPath)
      let uris = await AttachmentUtil.getUrisForSysFilemanager(fileType, fileName)
      const buff = new MemBuffer();
      buff.end(new Uint8Array(buffer));
      FileManager.saveData(buff, uris[0])
    } catch (error) {
      let err: BusinessError = error as BusinessError;
      logger.info("[picker] writeOnly error: " + JSON.stringify(err));
    }
  }

  /**
   * 获取文件在系统文件管理器中的目标路径
   * @param fileType 文件类型
   * @param fileName 文件名
   * @returns
   */
  static async getUrisForSysFilemanager(fileType:string, fileName:string): Promise<Array<string>> {
    switch (fileType) {
      case "img":
        const photoSaveOptions = new picker.PhotoSaveOptions(); // 创建图片管理器保存选项实例
        photoSaveOptions.newFileNames = [fileName];
        const photoViewPicker = new picker.PhotoViewPicker();
        let photoUris = await photoViewPicker.save(photoSaveOptions);
        return photoUris;
      case "auv":
        const audioSaveOptions = new picker.AudioSaveOptions(); // 创建音频文件管理器选项实例
        audioSaveOptions.newFileNames = [fileName];
        const audioViewPicker = new picker.AudioViewPicker();
        let audioUris = await audioViewPicker.save(audioSaveOptions)
        return audioUris;
      default:
        const documentSaveOptions = new picker.DocumentSaveOptions(); // 创建文档文件管理器选项实例
        documentSaveOptions.newFileNames = [fileName];
        const documentViewPicker = new picker.DocumentViewPicker();
        let documentUris = await documentViewPicker.save(documentSaveOptions);
        return documentUris
    }
  }
}